// API基础URL配置
const API_BASE_URL = 'http://localhost:5004';

// 检查并更新用户登录状态
async function updateUserLoginStatus() {
    const userInfoDiv = document.querySelector('.user-info');
    const authButtons = document.querySelector('.auth-buttons');
    const usernameDisplay = document.getElementById('username-display');

    // 获取最新的用户信息
    const userProfile = await fetchUserProfile();

    if (userProfile) {
        userInfoDiv.style.display = 'block';
        authButtons.style.display = 'none';
        usernameDisplay.textContent = userProfile.username;
    } else {
        userInfoDiv.style.display = 'none';
        authButtons.style.display = 'block';
    }
}

// 获取用户信息的函数
async function fetchUserProfile() {
    try {
        const token = localStorage.getItem('token');
        if (!token) return null;

        const response = await fetch(`${API_BASE_URL}/user/profile`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        const data = await response.json();
        if (data.code === 200) {
            return data.data;
        } else {
            console.error('获取用户信息失败:', data.message);
            return null;
        }
    } catch (error) {
        console.error('获取用户信息出错:', error);
        return null;
    }
}

// 退出登录处理函数
function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('token');
        localStorage.removeItem('user');

        const modal = document.getElementById('user-modal');
        if (modal) {
            modal.style.display = 'none';
        }

        showMessage('已成功退出登录');

        // 更新界面显示
        const userInfoDiv = document.querySelector('.user-info');
        const authButtons = document.querySelector('.auth-buttons');

        userInfoDiv.style.display = 'none';
        authButtons.style.display = 'block';

        window.location.href = 'index.html';
    }
}

// 消息提示函数
function showMessage(message) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message-toast';
    messageDiv.textContent = message;
    document.body.appendChild(messageDiv);

    setTimeout(() => messageDiv.classList.add('show'), 10);

    setTimeout(() => {
        messageDiv.classList.remove('show');
        setTimeout(() => messageDiv.remove(), 300);
    }, 3000);
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', function() {
    // 更新用户登录状态
    updateUserLoginStatus();

    // 设置用户详情模态窗口事件
    const usernameDisplay = document.getElementById('username-display');
    if (usernameDisplay) {
        usernameDisplay.onclick = async function() {
            const userProfile = await fetchUserProfile();
            if (userProfile) {
                const userModal = document.getElementById('user-modal');
                document.getElementById('modal-username').textContent = userProfile.username;
                document.getElementById('modal-email').textContent = userProfile.email;
                document.getElementById('modal-userid').textContent = userProfile.user_id;
                userModal.style.display = 'block';
            } else {
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                window.location.href = 'auth.html#login';
            }
        }
    }

    // 设置模态窗口关闭事件
    const closeButton = document.querySelector('.close-button');
    if (closeButton) {
        closeButton.onclick = function() {
            document.getElementById('user-modal').style.display = 'none';
        }
    }

    // 点击模态窗口外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('user-modal');
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    }
});

document.addEventListener('DOMContentLoaded', function() {
            // 获取模态窗口元素
            var contactModal = document.getElementById("contact-modal");
            var userModal = document.getElementById("user-modal");
            var contactLink = document.getElementById("contact-link");

            // 获取关闭按钮
            var contactCloseButton = document.querySelector("#contact-modal .close-button");
            var userCloseButton = document.querySelector("#user-modal .close-button");

            // 确保元素存在
            if (contactLink) {
                // 点击"联系方式"链接时显示模态窗口
                contactLink.addEventListener('click', function(event) {
                    event.preventDefault();
                    contactModal.style.display = "block";
                    console.log("联系方式模态窗口已打开");
                });
            }

            // 确保关闭按钮存在并添加事件监听器
            if (contactCloseButton) {
                contactCloseButton.addEventListener('click', function() {
                    contactModal.style.display = "none";
                    console.log("联系方式模态窗口已关闭");
                });
            }

            if (userCloseButton) {
                userCloseButton.addEventListener('click', function() {
                    userModal.style.display = "none";
                    console.log("用户模态窗口已关闭");
                });
            }

            // 点击模态窗口外部时隐藏模态窗口
            window.addEventListener('click', function(event) {
                if (event.target == contactModal) {
                    contactModal.style.display = "none";
                    console.log("点击外部关闭联系方式模态窗口");
                }
                if (event.target == userModal) {
                    userModal.style.display = "none";
                    console.log("点击外部关闭用户模态窗口");
                }
            });

            // 用户信息相关代码
            const userInfo = localStorage.getItem('user');
            const userInfoDiv = document.querySelector('.user-info');
            const authButtons = document.querySelector('.auth-buttons');
            const usernameDisplay = document.getElementById('username-display');
            if (userInfo) {
                const user = JSON.parse(userInfo);
                userInfoDiv.style.display = 'block';
                authButtons.style.display = 'none';
                usernameDisplay.textContent = user.username;

                // 点击用户名显示模态窗口
                usernameDisplay.addEventListener('click', function() {
                    const user = JSON.parse(localStorage.getItem('user'));
                    document.getElementById("modal-username").textContent = user.username;
                    document.getElementById("modal-email").textContent = user.email;
                    document.getElementById("modal-userid").textContent = user.id;
                    userModal.style.display = "block";
                    console.log("用户模态窗口已打开");
                });
            } else {
                userInfoDiv.style.display = 'none';
                authButtons.style.display = 'block';
            }
        });


//帮我详细注释这段代码：
// 1.获取历史作文列表
async function fetchEssayHistory() {
  try {
//    const userId = localStorage.getItem('user_id');
const userProfile = await fetchUserProfile();
        console.log(userProfile);
      // 获取用户ID（假设从 localStorage 中获取）
      const user_id = userProfile.user_id;
    if (!user_id) {
      throw new Error('用户未登录');
    }

// GET请求不应该有body，参数应该放在URL中
    const response = await fetch('http://127.0.0.1:5004/essay/history', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    });

    console.log('响应状态:', response.status);
 // 4. 处理响应
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `请求失败: ${response.status}`);
    }

    const result = await response.json();
    return Array.isArray(result.data) ? result.data : [];

  } catch (error) {
    console.error('获取历史作文失败:', error);
    showErrorToast('加载历史作文失败');
    return [];
  }
}

// 2. 修改渲染函数，直接使用获取到的数据
async function renderEssayList() {
  const container = document.getElementById('essay-list');
  container.innerHTML = '<div class="loading-state"><div class="spinner"></div><p>正在加载历史作文...</p></div>';

  try {
    const essays = await fetchEssayHistory();
    
    if (!essays || essays.length === 0) {
      container.innerHTML = `
        <div class="empty-state">
          <i class="fas fa-file-alt"></i>
          <p>暂无历史作文记录</p>
        </div>
      `;
      return;
    }

    container.innerHTML = essays.map(essay => `
      <div class="essay-item" data-essay-id="${essay.essay_id}" data-version-id="${essay.version_id}">
        <div class="essay-title">
          <i class="fas fa-file-alt"></i>
          <span>${essay.title || '无标题'}</span>
        </div>
        <div class="essay-date">
          <i class="far fa-calendar-alt"></i>
          <span>${formatDate(essay.created_at)}</span>
        </div>

      </div>
    `).join('');

    // 添加点击事件
    document.querySelectorAll('.essay-item').forEach(item => {
      item.addEventListener('click', async () => {
        try {
          const essayId = item.dataset.essayId;
          const versionId = item.dataset.versionId;
console.log('essayId 类型:', typeof essayId, '值:', essayId);
console.log('versionId 类型:', typeof versionId, '值:', versionId);
const scoreData = await fetchEssayScore(essayId, versionId);
renderScoreModal(scoreData);
        } catch (error) {
          console.error('获取评分详情失败:', error);
          showErrorToast('获取评分详情失败，请稍后重试');
        }
      });
    });

  } catch (error) {
    console.error('渲染作文列表失败:', error);
    container.innerHTML = `
      <div class="error-state">
        <i class="fas fa-exclamation-triangle"></i>
        <p>加载失败，请刷新重试</p>
      </div>
    `;
  }
}

// 获取作文评分详情
async function fetchEssayScore(essayId, versionId) {
  try {
   // 构造查询参数
    const queryParams = new URLSearchParams({
      essay_id: essayId,
      version_id: versionId
    });

    // 发送GET请求（注意接口路径是/essay/analysis不带参数路径）
    const response = await fetch(`http://127.0.0.1:5004/essay/analysis?${queryParams}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      },
//      credentials: 'include' // 如果需要携带cookie
    });
//    const response = await fetch(`http://127.0.0.1:5004/essay/analysis?${essayId}?${versionId}`, {
//      method: 'GET',
//      headers: {
//        'Authorization': `Bearer ${localStorage.getItem('token')}`,
//        'Content-Type': 'application/json'
//      }
//    });

    if (!response.ok) {
      throw new Error('获取评分详情失败');
    }

    const result = await response.json();
    console.log(result);
    if (result.code === 200) {
      return result.data;
    } else {
      throw new Error(result.message || '获取评分详情失败');
    }
  } catch (error) {
    console.error('获取评分详情出错:', error);
    throw error;
  }
}

// 渲染评分弹窗
function renderScoreModal(data) {
  const modal = document.getElementById('score-modal');
  if (!modal) {
    console.error('未找到评分弹窗元素');
    return;
  }

  // 更新总体评分
  const overallScoreElement = modal.querySelector('.overall-score .score-value');
  if (overallScoreElement) {
    overallScoreElement.textContent = data.overall_score || '0';
    const progress = modal.querySelector('.progress-bar');
    if (progress) {
      progress.style.width = `${data.overall_score || 0}%`;
    }
  }
// 各维度评分
  const dimensions = {
    vocabulary: data.vocabulary_score?.total,
    sentence: data.sentence_score?.total,
    structure: data.structure_score?.total,
    content: data.content_score?.total
  };

  Object.entries(dimensions).forEach(([dimension, score]) => {
    const element = modal.querySelector(`.${dimension} .dimension-value`);
    if (element) element.textContent = score || '0';
  });
//  // 更新各维度评分
//  const scoreDetails = modal.querySelector('.score-details');
//  if (scoreDetails) {
//    scoreDetails.innerHTML = `
//      <div class="score-item">
//        <span class="score-category">词汇评分</span>
//        <span class="score-number">${data.vocabulary_score?.total || '0'}</span>
//      </div>
//      <div class="score-item">
//        <span class="score-category">句子评分</span>
//        <span class="score-number">${data.sentence_score?.total || '0'}</span>
//      </div>
//      <div class="score-item">
//        <span class="score-category">结构评分</span>
//        <span class="score-number">${data.structure_score?.total || '0'}</span>
//      </div>
//      <div class="score-item">
//        <span class="score-category">内容评分</span>
//        <span class="score-number">${data.content_score?.total || '0'}</span>
//      </div>
//    `;
//  }

//  // 更新优秀句子
//  const sentenceList = modal.querySelector('.sentence-list');
//  if (sentenceList && Array.isArray(data.good_sentences)) {
//    sentenceList.innerHTML = data.good_sentences
//      .map(sentence => `<li>${sentence}</li>`)
//      .join('');
//  }
//
//  // 更新改进建议
//  const suggestionList = modal.querySelector('.suggestion-list');
//  if (suggestionList && Array.isArray(data.suggestions)) {
//    suggestionList.innerHTML = data.suggestions
//      .map(suggestion => `<li>${suggestion}</li>`)
//      .join('');
//  }
// 优秀句子
  const sentenceList = modal.querySelector('.good-sentences .feedback-list');
  if (sentenceList) {
//    sentenceList.innerHTML = (data.excellent_expressions.quote || []).map(sentence => `
//      <li>
//        <i class="fas fa-quote-left"></i>
//        ${sentence}
//      </li>
//    `).join('') || '<li>暂无优秀句子</li>';
// 渲染优秀句子列表（匹配图片样式）
const sentenceList = modal.querySelector('.good-sentences .feedback-list');
if (sentenceList) {
  sentenceList.innerHTML = data.excellent_expressions?.length
    ? data.excellent_expressions.map(item => `
        <li class="sentence-item">
          <div class="quote-content">
            <i class="fas fa-quote-left quote-icon"></i>
            ${item.quote}
          </div>
          <div class="quote-reason">
            <i class="fas fa-lightbulb reason-icon"></i>
            ${item.reason}
          </div>
        </li>
      `).join('')
    : '<li class="no-sentence">暂无优秀句子</li>';
}
  }

  // 改进建议
  const suggestionList = modal.querySelector('.suggestions .feedback-list');
  if (suggestionList) {
    suggestionList.innerHTML = (data.suggestions || []).map(suggestion => `
      <li>
        <i class="fas fa-chevron-right"></i>
        ${suggestion}
      </li>
    `).join('') || '<li>暂无改进建议</li>';
  }

  // 显示弹窗
  modal.classList.remove('hidden');
  modal.classList.add('show');
}

// 格式化日期
function formatDate(isoString) {
  return new Date(isoString).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
}

// 显示错误提示
function showErrorToast(message) {
  const toast = document.createElement('div');
  toast.className = 'error-toast';
  toast.textContent = message;
  document.body.appendChild(toast);

  setTimeout(() => {
    toast.classList.add('show');
  }, 10);

  setTimeout(() => {
    toast.classList.remove('show');
    setTimeout(() => toast.remove(), 300);
  }, 3000);
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
  renderEssayList();

  // 添加弹窗关闭事件
  const closeBtn = document.querySelector('.close-btn');
  if (closeBtn) {
    closeBtn.addEventListener('click', () => {
      const modal = document.getElementById('score-modal');
      modal.classList.remove('show');
      modal.classList.add('hidden');
    });
  }

  // 点击弹窗外部关闭
  window.addEventListener('click', (event) => {
    const modal = document.getElementById('score-modal');
    if (event.target === modal) {
      modal.classList.remove('show');
      modal.classList.add('hidden');
    }
  });
});